package com.onlyxiahui.aware.extend.shardingsphere.algorithm;

import java.util.Collection;
import java.util.Random;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

/**
 * 
 * 
 * 随机分片<br>
 * Date 2019-08-26 10:57:23<br>
 * 
 * @author XiaHui [onlovexiahui@qq.com]<br>
 * @since 1.0.0
 */
public class RandomPreciseShardingAlgorithm implements PreciseShardingAlgorithm<String> {

	Random r = new Random();

	@Override
	public String doSharding(final Collection<String> databaseNames, final PreciseShardingValue<String> shardingValue) {
		// 计算当前分片值所在的节点号
		int size = databaseNames.size();
		int index = r.nextInt(size);
		// 找到匹配的数据库名称并返回
		int i = 0;
		for (String databaseName : databaseNames) {
			if (i == index) {
				return databaseName;
			}
			i++;
		}
		throw new UnsupportedOperationException();
	}
}
